package com.weixing.mall.provider.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.model.vo.SysConfigVo;
import com.weixing.mall.provider.api.model.vo.SysUserVo;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.mapper.MediaPlatformMapper;
import com.weixing.mall.provider.mapper.RoleMapper;
import com.weixing.mall.provider.model.domain.MediaPlatform;
import com.weixing.mall.provider.model.domain.Role;
import com.weixing.mall.provider.model.dto.ads.MediaPlatformDto;
import com.weixing.mall.provider.model.enums.WhetherEnum;
import com.weixing.mall.provider.model.enums.sys.SysFlag;
import com.weixing.mall.provider.model.query.MediaPlatformQuery;
import com.weixing.mall.provider.model.vo.ads.MediaPlatformEditVo;
import com.weixing.mall.provider.model.vo.ads.MediaPlatformVo;
import com.weixing.mall.provider.service.IConfigService;
import com.weixing.mall.provider.service.IMediaPlatformService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 广告模块-媒体平台表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-18
 */
@Service
public class MediaPlatformServiceImpl extends ServiceImpl<MediaPlatformMapper, MediaPlatform> implements IMediaPlatformService {

    @Autowired
    private RoleMapper sysRoleMapper;
    @Autowired
    private IConfigService sysConfigService;

    @Override
    public IPage<MediaPlatformVo> selectOfPage(Page initMpPage, MediaPlatformQuery mediaPlatformQuery, Long uid) {

        List<Role> roleList = sysRoleMapper.selectSysRoleByUserId(uid, SysFlag.SYS.getValue());
        int qs = 0;
        ArrayList<Integer> numList = new ArrayList<Integer>();
        for (int i = 0; i < roleList.size(); i++) {
            //角色code是director（广告专员），就只能查自己的
            if ("director".equals(roleList.get(i).getRoleCode())) {
                qs = 1;
            } else if ("customer".equals(roleList.get(i).getRoleCode())) {//角色code是customer（广告客服），查客服所属的
                qs = 2;
            } else {//否则查全部的
                qs = 3;
            }
            numList.add(qs);
        }
        //取出最大值
        int type = Collections.max(numList);
        if (type == 1) {//广告专员
            // mediaPlatformQuery.setCreatedBy(uid);
            mediaPlatformQuery.setDirector(uid);
        } else if (type == 2) {//广告客服
            mediaPlatformQuery.setCreatedBy(null);
            mediaPlatformQuery.setCustomerId(uid);
        } else {//全部，自由操控

        }

        return baseMapper.selectOfPage(initMpPage, mediaPlatformQuery);
    }

    @Override
    public List<MediaPlatformVo> selectMediaPlatFromList(MediaPlatformQuery mediaPlatformQuery, Long uid) {
        List<Role> roleList = sysRoleMapper.selectSysRoleByUserId(uid, SysFlag.SYS.getValue());
        int qs = 0;
        ArrayList<Integer> numList = new ArrayList<Integer>();
        for (int i = 0; i < roleList.size(); i++) {
            //角色code是director（广告专员），就只能查自己的
            if ("director".equals(roleList.get(i).getRoleCode())) {
                qs = 1;
            } else if ("customer".equals(roleList.get(i).getRoleCode())) {//角色code是customer（广告客服），查客服所属的
                qs = 2;
            } else {//否则查全部的
                qs = 3;
            }
            numList.add(qs);
        }
        //取出最大值
        int type = Collections.max(numList);
        if (type == 1) {//广告专员
            // mediaPlatformQuery.setCreatedBy(uid);
            mediaPlatformQuery.setDirector(uid);
        } else if (type == 2) {//广告客服
            mediaPlatformQuery.setCreatedBy(null);
            mediaPlatformQuery.setCustomerId(uid);
        } else {//全部，自由操控

        }
        return baseMapper.selectOfPage(mediaPlatformQuery);
    }

    @Override
    public void save(MediaPlatformDto mediaPlatformDto) {
        MediaPlatform mediaPlatform = new MediaPlatform();
        BeanUtils.copyProperties(mediaPlatformDto, mediaPlatform);
        if (ObjectUtil.isNotEmpty(mediaPlatform) && mediaPlatform.getDirector() == null) {//若前端未选择广告专员 则默认当前用户为广告专员
            SysAuth auth = AuthUtil.getSysExt();
            mediaPlatform.setDirector(auth.getUid());
        }
        mediaPlatform.setPageSite(mediaPlatformDto.getPageSite().getValue());
      if (mediaPlatformDto.getId() == null) {
            //校验名称是否重复
            /*  if (!checkPlateformNameOnly(mediaPlatform.getPlateformName())) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("plateform_name", mediaPlatformDto.getPlateformName());
                MediaPlatform mediaPlatform1 = getOne(queryWrapper);
                Result<SysUserVo> result = sysUserRpcService.getById(mediaPlatform1.getCreatedBy());
                String msg = "";
                if (result.isSuccess()) {
                    msg = result.getData().getRealName();
                }
                throw new BusinessException("媒体平台已经被" + msg + "录入");
            }*/
            mediaPlatform.setIsPubPool(0);
          mediaPlatform.setCreatedBy(mediaPlatformDto.getCreatBy());
            save(mediaPlatform);
        } else {
            //二期更新的时候也需要检查是否有重复
           /* QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("plateform_name", mediaPlatformDto.getPlateformName());
            MediaPlatform mediaPlatform1 = getOne(queryWrapper);
            if (null != mediaPlatform1) {
                if (mediaPlatform1.getId().longValue() != mediaPlatformDto.getId().longValue()) {
                    Result<SysUserVo> result = sysUserRpcService.getById(mediaPlatform1.getCreatedBy());
                    String msg = "";
                    if (result.isSuccess()) {
                        msg = result.getData().getRealName();
                    }
                    throw new BusinessException("媒体平台已经被" + msg + "录入");
                }

            }*/
          mediaPlatform.setUpdatedBy(mediaPlatformDto.getCreatBy());
            updateById(mediaPlatform);
        }
    }

    @Override
    public IPage<MediaPlatformVo> selectOfPagePub(Page initMpPage, MediaPlatformQuery mediaPlatformQuery) {
        return baseMapper.selectByIsPubPool(initMpPage, mediaPlatformQuery);
    }

    @Override
    public void updateIsPubPool(Long[] ids) {
        List list = new ArrayList<>();
        for (Long id : ids) {
            list.add(id);
        }
        baseMapper.updateIsPubPool(list);
    }

    @Override
    public void claim(Long[] ids, Long uid) {
        ArrayList<MediaPlatform> list = new ArrayList<>();
        for (Long id : ids) {
            MediaPlatform mediaPlatform = new MediaPlatform();
            mediaPlatform.setId(id);
            mediaPlatform.setDirector(uid);
            list.add(mediaPlatform);
        }
        baseMapper.claim(list);
    }

    @Override
    public MediaPlatformEditVo selectMediaPlatformEditVo(Long id) {
        return baseMapper.selectMediaPlatformEditVoById(id);
    }

    @Override
    public int getPublic() {
        DateTime date = new DateTime();
        SysConfigVo vo = sysConfigService.selectVoByCfgCode(GlobalConstant.PUBLIC_POOL_DAY);
        int day = vo.getCfgValue().intValue();
        String startTime = DateUtil.format(DateUtil.offset(date, DateField.DAY_OF_YEAR, day * -1), "yyyy-MM-dd");
        SysConfigVo vo2 = sysConfigService.selectVoByCfgCode(GlobalConstant.PUBLIC_POOL_WAIT);
        DateTime date2 = new DateTime();
        int day2 = day - vo2.getCfgValue().intValue();
        String endTime = DateUtil.format(DateUtil.offset(date2, DateField.DAY_OF_YEAR, day2 * -1), "yyyy-MM-dd");
        return baseMapper.findPublic(startTime, endTime);
    }

    @Override
    public void del(Long id) {
        MediaPlatform mp = getById(id);
        if (ObjectUtil.isEmpty(mp)) {
            new BusinessException("媒体信息不存在，请刷新后重试");
        }
        if (WhetherEnum.YES.getValue().equals(mp.getUsedStatus())) {
            new BusinessException("媒体信息已被使用不可删除");
        }
        baseMapper.deleteById(id);
    }

    @Override
    public boolean checkPlateformNameOnly(String plateformName) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("plateform_name", plateformName);
        return count(queryWrapper) > 0 ? false : true;
    }
}
